// pages/postMoment/postMoment.js
let app = getApp()

import req from '../../utils/req';
import utils from '../../utils/utils';

Page({

  /**s
   * 页面的初始数据
   */
  data: {
    photo: [],
    description: '',
    title: '',
    budget: '',
    people: '',
    taps: [''],
    height: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let height = 0
    wx.getSystemInfo({
      success: res => {
        height = res.windowHeight;
      }
    });
    this.setData({
      height,
      type: options.type
    })
  },

  chooseImage: function (e) {
    var that = this;
    const avalibleNum = 9 - that.data.photo.length;
    wx.chooseImage({
      count: avalibleNum,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          photo: that.data.photo.concat(res.tempFilePaths)
        });
      }
    })
  },

  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.photo // 需要预览的图片http链接列表
    })
  },

  deletePhoto(e) {
    const photo = this.data.photo;
    photo.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      photo
    })
  },

  post() {
    if (this.dataIsNull()) {
      let id = utils.randomId()
      let type = this.data.type
      if (type === 'normal') {
        if (this.data.photo.length === 0) {
          this.postMoment(id)
        } else {
          this.uploadImg(id, 'mid', (res) => {
            if (res) {
              setTimeout(() => {
                this.postMoment(id);
              }, 3000)
            } else {
              utils.toast("error", "发布失败");
            }
          })
        }
      } else {
        this.uploadImg(id, 'sid', (res) => {
          if (res) {
            setTimeout(() => {
              this.postStrategy(id);
            }, 3000)
          } else {
            utils.toast("error", "发布失败");
          }
        })
      }
    }
  },

  description(e) {
    this.setData({
      description: e.detail.value
    })
  },
  title(e) {
    this.setData({
      title: e.detail.value
    })
  },
  budget(e) {
    this.setData({
      budget: e.detail.value
    })
  },
  people(e) {
    this.setData({
      people: e.detail.value
    })
  },

  uploadImg(id, type, back) {
    const _id = type === 'mid' ? {
      mid: id
    } : {
      sid: id
    }
    req._uploadFile('上传图片中', '/img/upload', this.data.photo, _id, (res) => {
      return back(res)
    })
  },

  postMoment(mid) {
    const data = {
      mid,
      description: this.data.description,
      uid: app.globalData.userInfo.uid
    }
    req.post('发布中', '/moment/createMoment', data, (res) => {
      utils.toast("success", res.msg);
      this.setData({
        photo: [],
        description: ''
      })
      utils.back()
    })
  },

  postStrategy(sid) {
    const taps = this.data.taps.toString()
    const data = {
      sid,
      taps,
      title: this.data.title,
      description: this.data.description,
      uid: app.globalData.userInfo.uid,
      budget: this.data.budget,
      people: this.data.people
    }
    req.post('发布中', '/moment/createStrategy', data, (res) => {
      utils.toast("success", res.msg);
      this.setData({
        photo: [],
        title: '',
        description: '',
        taps: [''],
        budget: '',
        people: ''
      })
      utils.back()
    })
  },

  inputTips(e) {
    const taps = this.data.taps
    taps[e.currentTarget.dataset.index] = e.detail.value
    this.setData({
      taps
    })
  },

  addTips(e) {
    const taps = this.data.taps
    taps.splice(e.currentTarget.dataset.index + 1, 0, '')
    this.setData({
      taps
    })
  },
  reduceTips(e) {
    const taps = this.data.taps
    taps.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      taps
    })
  },
  dataIsNull() {
    const description = this.data.description
    const title = this.data.title
    const photo = this.data.photo
    const taps = this.data.taps
    const type = this.data.type
    const budget = this.data.budget
    const people = this.data.people
    const back = false
    if (type === 'normal') {
      if (description === '') {
        utils.toast('warn', '文字不能为空')
        return back
      } else {
        return !back
      }
    } else {
      if (title === '') {
        utils.toast('warn', '主题不能为空')
        return back
      } else if (description === '') {
        utils.toast('warn', '描述不能为空')
        return back
      } else if (photo.length === 0) {
        utils.toast('warn', '图片不能为空')
        return back
      } else if (taps.find(i => i === '') === '') {
        utils.toast('warn', '标签不能为空')
        return back
      } else if (budget === '') {
        utils.toast('warn', '预算不能为空')
        return back
      } else if (people === '') {
        utils.toast('warn', '人数不能为空')
        return back
      }
      return !back
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let pages = getCurrentPages(); //页面栈
    let beforePage = pages[pages.length - 2];
    beforePage.setData({
      tabIndex: this.data.type === 'normal' ? 0 : 1
    })
    beforePage.onLoad()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})